/*
 * All rights Reserved, Designed By cloudland Copyright(C) 2010-2014
 *
 * fileName:  SessionProxyRequest.java
 * author:  lei
 * Company:  Cloudland Studio
 * Createdate:  2013-9-14 下午1:05:08
 *   
 * Modification  History:
 *     Date           Author        Version        
 * -------------------------------------------
 * 2013-9-14          Lei            1.0        
 *
 * Why & What is modified:
 * 1.0: 文件创建
 */
package org.cloudland.web.context.request;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpSession;

import org.cloudland.web.context.support.SessionInvocationHandler;

 /**
 * <pre> 
 * Session 代理。用做分布式集群共享 Session
 * </pre>
 * @ClassName  SessionProxyRequest
 * @author  lei
 * @version  %I%, %G%
 * @see  
 * @since   JDK1.6
 *
 */
public class SessionProxyRequest extends HttpServletRequestWrapper {

	/**
     * jsessionId 缓存的 SessionId
     */
    private String jsessionId;
    
    /**
     * SESSION_PROXY_KEY 存放 session 代理对象
     */
    private final static String SESSION_PROXY_KEY = "cloudland_session_proxy";
    
    /** 
     * default constructor
     */
    public SessionProxyRequest(HttpServletRequest request, String sessionId)
    {
        super(request);
        this.jsessionId = sessionId;
    }
    
    /**
     * @return
     */
    @Override
    public HttpSession getSession()
    {
        return this.getSession(true);
    }
    
    /**
     * @param create
     * @return
     */
    @Override
    public HttpSession getSession(boolean create)
    {
        HttpSession session = super.getSession(create);
        if (session != null) {
            Object proxy = session.getAttribute(SESSION_PROXY_KEY);
            if (null == proxy) {
                InvocationHandler sessionProxy = new SessionInvocationHandler(session, jsessionId);
                proxy = Proxy.newProxyInstance(HttpSession.class.getClassLoader(), new Class<?>[]{HttpSession.class}, sessionProxy);
                session.setAttribute(SESSION_PROXY_KEY, proxy);
            }
            
            session = (HttpSession)proxy;
        }
        return session;
    }
}
